import json
import os
import uuid

from django.db.models.functions import datetime
from django.utils.autoreload import logger
from rest_framework.response import Response
from rest_framework.views import APIView
from django.utils import timezone

from backend import settings
from utils.auth import *

from common.response_code import ResponseCode
from user.serializers import *


# 注册接口
class RegisterAPIView(APIView):
    @staticmethod
    def generate_default_username(length):
        uuid_str = str(uuid.uuid4()).replace('-', '')
        default_username = 'COJ用户_' + uuid_str[:length]
        return default_username

    @staticmethod
    def check_account(account) -> bool:
        try:
            data = User.objects.filter(account = account).values().first()
            if not data:
                return False
            else:
                return True
        except Exception as e:
            # 服务器可能异常
            logger.info(e)

    def post(self, request):
        try:
            data = json.loads(request.body)
            # 先检查账号是否被注册
            check_account_res = self.check_account(data["account"])
            if check_account_res:
                # 返回账号已被注册的错误信息
                return Response({
                        "code": ResponseCode.ACCOUNT_EXISTS.value[0],
                        "message": ResponseCode.ACCOUNT_EXISTS.value[1]
                    })
            else:
                # 可以注册
                data["create_datetime"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                # 生成一个默认用户名
                default_username = self.generate_default_username(16)
                data["username"] = default_username
                # 生成一个非法token，不要让token为空
                data['token'] = 'null'
                serializer = UserRegisterSerializer(data = data)
                if serializer.is_valid():
                    serializer.save()
                    # 返回注册成功信息
                    return Response({
                            "code": ResponseCode.SUCCESS.value[0],
                            "message": ResponseCode.SUCCESS.value[1]
                        })

                else:
                    return Response(
                        {
                            "code": ResponseCode.INVALID_ERROR.value[0],
                            "message": ResponseCode.INVALID_ERROR.value[1]
                        })

        except Exception as e:
            return Response({
                    "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                    "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1]
                })


# 登录接口
class LoginAPIView(APIView):
    def post(self, request):
        try:
            login_request = json.loads(request.body)
            account = login_request["account"]
            password = login_request["password"]
            user = User.objects.filter(account = account, password = password).first()
            if not user:
                return Response({
                    "code": ResponseCode.ACCOUNT_OR_PASSWORD_ERROR.value[0],
                     "message": ResponseCode.ACCOUNT_OR_PASSWORD_ERROR.value[1]
                })

            token = str(uuid.uuid4()).replace('-', '')
            # 将token添加至用户
            user.token = token
            user.save()

            # 返回登录成功信息以及token
            return Response({
                    "code": ResponseCode.SUCCESS.value[0], "message": ResponseCode.SUCCESS.value[1],
                    "token": token,
                })

        except Exception as e:
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                 "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1]
            })


# 获取用户信息接口
class GetUserInfoAPIView(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]

    def get(self, request):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })

            return Response({
                    "code": ResponseCode.SUCCESS.value[0], "message": ResponseCode.SUCCESS.value[1],
                    "user": UserLoginSerializer(instance = request.user).data,
                })


        except Exception as e:
            print(e)
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })


# 修改用户信息接口
class ModifyUserInfoAPIView(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]

    def post(self, request):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })

            # 获取修改信息
            username = request.POST.get("username")
            user = request.user
            user.username = username
            user.save()
            return Response({
                    "code": ResponseCode.SUCCESS.value[0],
                    "message": ResponseCode.SUCCESS.value[1]
                })

        except Exception as e:
            print(e)
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })


# 修改密码接口
class ModifyPasswordAPIView(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]

    def post(self, request):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })

            # 获取旧密码和新密码
            data = json.loads(request.body)
            old_password = data["oldPassword"]
            new_password = data["newPassword"]
            user = request.user
            print(user.password)
            print(old_password)

            if old_password == user.password:
                if new_password == user.password:
                    # 新密码与原来相同
                    return Response({
                        "code": ResponseCode.NEWPASSWORD_EXISTS.value[0],
                        "message": ResponseCode.NEWPASSWORD_EXISTS.value[1]
                    })

                else:
                    # 允许修改
                    user.password = new_password
                    user.save()
                    return Response(
                        {
                            "code": ResponseCode.SUCCESS.value[0],
                            "message": ResponseCode.SUCCESS.value[1]
                        })
            else:
                return Response({
                    "code": ResponseCode.OLDPASSWORD_ERROR.value[0],
                    "message": ResponseCode.OLDPASSWORD_ERROR.value[1]
                })


        except Exception as e:
            print(e)
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })


# 修改用户头像
class ModifyAvatarAPIView(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]

    def post(self, request):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })
            
            # 生成时间戳
            timestamp = str(int(timezone.now().timestamp()))[:10]

            # 获取图片文件
            file = request.FILES.get('avatar', None)
            # 根据用户id修改文件名
            filename = str(request.user.id) + "_" + timestamp + ".jpg"

            file_path = os.path.join(settings.AVATAR_ROOT, filename)

            

            # 写入文件
            with open(file_path, 'wb+') as f:
                for chunk in file.chunks():
                    f.write(chunk)

                request.user.avatar_url = settings.AVATAR_URL + str(request.user.id) + "_" + timestamp + ".jpg"
                request.user.save()
                print(request.user.avatar_url)
                return Response(
                    {
                        "code": ResponseCode.SUCCESS.value[0],
                        "message": ResponseCode.SUCCESS.value[1],
                        "avatarUrl": request.user.avatar_url
                    })

        except Exception as e:
            print(e)
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })
